package leetcode;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 描述:116. 填充每个节点的下一个右侧节点指针
 *
 * @author Madison You
 * @created 9:16
 */
public class Mid_116_Connect {
    public static void main(String[] args) {

    }

    public Node connect(Node root) {
        Queue<Node> queue = new LinkedBlockingQueue<>();
        if (root == null) return root;
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            Node pre = queue.poll();
            for (int i = 1; i < size; i++) {
                Node node = queue.poll();
                pre.next = node;
                pre = node;
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return root;
    }

    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;
        public Node() {}
        public Node(int _val) {
            val = _val;
        }
        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
